package com.clj.blesample;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.clj.blesample.entity.Record;
import com.clj.blesample.entity.Result;
import com.clj.blesample.udp.UdpClient;
import com.clj.fastble.utils.HexUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TestUdpActivity extends AppCompatActivity implements UdpClient.OnDataReceiveListener {
    private TextView txt;
    private EditText etContent;
    private Timer timer;
    private boolean isStartUdp;
    private Disposable mDisposable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_udp);
        txt = findViewById(R.id.tvLog);
        etContent = findViewById(R.id.etContent);
        etContent.setText("1480202020200000006d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002020202139352020202020202020202049450020000000006400d100018b0042003c0004012c000000f11e2302092031000000000000000000005134");
        connectUdp();
        findViewById(R.id.startRecord).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDisposable.dispose();
//                if (UdpClient.getInstance().isConnect()) {
//                    String content = etContent.getText().toString();
//                    byte[] data = HexUtil.hexStringToBytes(content);
//                    byte[] data1 = new byte[104];
//                    for (int i = 0; i < data1.length; i++) {
//                        data1[i] = data[i];
//                    }
//                    String result = HexUtil.formatHexString(data1);
//                    Log.d("jiajia", result);
//                    Log.d("jiajia", "长度：" + data.length);
//                    Log.d("jiajia", "长度：" + content.length());
////                    send(data);
////                    uploadData(content);
//                } else {
//                    Toast.makeText(TestUdpActivity.this, "尚未连接，请连接Socket", Toast.LENGTH_SHORT).show();
//                }
            }
        });

        mDisposable = Observable.interval(300,300, TimeUnit.MILLISECONDS)
                .observeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        Log.d("jiajia", aLong + "------>");
                    }
                });
    }

    private void uploadData(final String data) {
        Executors.newCachedThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    List<Record> records = new ArrayList<>();
                    records.add(new Record(1.0f, 2.0f, "2023-02-06 11:21:00"));
                    records.add(new Record(1.0f, 2.0f, "2023-02-06 11:21:00"));
                    records.add(new Record(1.0f, 2.0f, "2023-02-06 11:21:00"));
                    records.add(new Record(1.0f, 2.0f, "2023-02-06 11:21:00"));
                    records.add(new Record(1.0f, 2.0f, "2023-02-06 11:21:00"));
                    records.add(new Record(1.0f, 2.0f, "2023-02-06 11:21:00"));
                    records.add(new Record(1.0f, 2.0f, "2023-02-06 11:21:00"));
                    records.add(new Record(1.0f, 2.0f, "2023-02-06 11:21:00"));
                    records.add(new Record(1.0f, 2.0f, "2023-02-06 11:21:00"));
                    records.add(new Record(1.0f, 2.0f, "2023-02-06 11:21:00"));
                    Gson gson = new Gson();
                    String json = gson.toJson(records);
                    final String no = data.substring(4, 12);
                    final String rNo = data.substring(12, 20);
                    String fileName = Integer.parseInt(no, 16) + "_" + Integer.parseInt(rNo, 16) + ".json";
                    File cacheFile = new File(getCacheDir(), fileName);
                    if (cacheFile.exists()) {
                        cacheFile.delete();
                    }
                    BufferedWriter bfw = new BufferedWriter(new FileWriter(cacheFile, true));
                    bfw.write(json);
                    bfw.newLine();
                    bfw.flush();
                    bfw.close();
                    RequestBody body = new MultipartBody.Builder()
                            //一定要设置这句
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("file", fileName, RequestBody.create(MediaType.parse("application/octet-stream"), cacheFile))
                            .build();

                    Request request = new Request.Builder()
                            .url("http://47.111.144.84:82/FileUpload")
                            .post(body)
                            .build();
                    OkHttpClient client = new OkHttpClient();
                    Response execute = client.newCall(request).execute();
                    if (execute.code() == 200) {
                        //上传成功
                        String resultJson = execute.body().string();
                        final Result<String> result = gson.fromJson(resultJson, new TypeToken<Result<String>>() {
                        }.getType());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (result.code == 200) {
                                    Toast.makeText(TestUdpActivity.this, "数据上传成功", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(TestUdpActivity.this, "数据上传失败，" + result.info, Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                } catch (final IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(TestUdpActivity.this, "数据上传失败，" + e, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });

    }

    /**
     * socket send
     */
    private void send(final byte[] data) {
        isStartUdp = true;
        Executors.newCachedThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    if (!isStartUdp) {
                        return;
                    }
                    addText(txt, "第" + (i + 1) + "次发送");
                    UdpClient.getInstance().sendByteCmd(data, 1001);
                    try {
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        addText(txt, "5次发送udp都未能收到响应");
                        Toast.makeText(TestUdpActivity.this, "udp服务器异常请检查", Toast.LENGTH_SHORT).show();
                        isStartUdp = false;
                    }
                });
            }
        });
        UdpClient.getInstance().sendByteCmd(data, 1001);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UdpClient.getInstance().disconnect();
    }

    private void connectUdp() {
        UdpClient.getInstance().setOnDataReceiveListener(this);
        UdpClient.getInstance().connect("47.111.144.84", 10010);
    }

    @Override
    public void onConnectSuccess() {
        addText(txt, "udp连接成功");
//        startHeartbeatTimer();
    }

    @Override
    public void onConnectFail() {
        addText(txt, "udp连接失败");
    }

    @Override
    public void onDataReceive(byte[] buffer, int size, int requestCode) {
        addText(txt, "接收到udp数据1111：" + HexUtil.formatHexString(buffer));
        if (requestCode == 1001) {
            isStartUdp = false;
            addText(txt, "接收到udp数据：" + HexUtil.formatHexString(buffer));
        } else if (requestCode == 1000) {
            addText(txt, "接收到udp心跳：" + HexUtil.formatHexString(buffer));
        }
    }

    private void addText(final TextView textView, final String content) {
        textView.post(new Runnable() {
            @Override
            public void run() {
                textView.append(content);
                textView.append("\n");
                int offset = textView.getLineCount() * textView.getLineHeight();
                if (offset > textView.getHeight()) {
                    textView.scrollTo(0, offset - textView.getHeight());
                }
            }
        });

    }


}
